/**
 * Created by moyu on 2017/4/7.
 */

const renderer = require('express')();
const wrap = require('express-async-wrap');
const moment = require('moment');
const ObjectId = require('mongodb').ObjectId;
const articleDB = require('../db/article');


renderer.use((req, res, next) => {
    if (!req.login) {
        res.redirect("/");
        return;
    }
    next();
});

renderer.all("/", (req, res, next) => {
    let data = require('../data/weibo.json').reduce((p, a) => {
        p[a.category||"微博"] = p[a.category||"微博"] || [];
        p[a.category||"微博"].push(a);
        return p;
    }, {});

    if (req.ent.update) {
        articleDB.findOne({_id: ObjectId(req.ent.update)})
            .then(doc => {
                res.render("admin", {
                    title: "管理员",
                    active: 'admin',
                    login: req.login,
                    update: req.ent.update,
                    defaultTitle: doc.title,
                    defaultContent: doc.content,
                    defaultTags: doc.tags.join(','),
                    defaultTop: doc.top == 1,
                    emoji: data
                })
            }).catch((err) => res.send(err))
    } else {
        res.render("admin", {
            title: "管理员",
            active: 'admin',
            login: req.login,
            emoji: data
        })
    }
});



module.exports = renderer;